# -*- coding: utf-8 -*-
'''
| @author: olivia.dou
| Created on: 2019/6/5 17:08
| desc: 通用的验证数据函数
'''
import logging
from jsonpath import jsonpath
from util.jsonmatch import jsonmatch



def validate_result(testcase, testdata, pattern_items_all, data_fmt_map=None):
    '''
    通用的验证数据函数

    :param testcase:
    :param testdata: 基准数据
    :param pattern_items_all: 匹配结果的完整列表的模式
    :param data_fmt_map: 补充结果信息

    :return: 无
    '''


    res_json = testcase.response.json()
    if not hasattr(testcase, 'end_field_index') or testcase.end_field_index is None:
        test_data_fields = list(testdata.keys())[testcase.start_field_index:]
    else:
        test_data_fields = list(testdata.keys())[testcase.start_field_index:testcase.end_field_index]

    result_fields = [field.split('.')[-1] for field in test_data_fields]

    # 验证各字段一一对应
    expected_result = []
    #expected_base_values = str(testdata[test_data_fields[0]]).split('|')
    if data_fmt_map and test_data_fields[0] in data_fmt_map:
        expected_base_values = list(map(data_fmt_map[test_data_fields[0]], testdata[test_data_fields[0]].split('|')))
    else:
        expected_base_values = str(testdata[test_data_fields[0]]).split('|')
    # for i in range(len(expected_names)):
    #     # 将对应位置的各字段值组合起来
    #     item = {}
    #     for field in target_fields:
    #         item[field] = testdata[field].split('|')[i]
    #     expected_result.append(item)

    # 按字段迭代, 因需先对字段值进行类型转换
    # 先给列表赋n个字典
    for i in range(len(expected_base_values)):
        expected_result.append({})
    for field in test_data_fields:
        # 数据转换
        if data_fmt_map and field in data_fmt_map:
            data_list = list(map(data_fmt_map[field],testdata[field].split('|')))
        else:
            data_list = str(testdata[field]).split('|')
        for i in range(len(expected_base_values)):
            expected_result[i][field.split('.')[-1]] = data_list[i] #Todo 改进？

    logging.debug(expected_result)

    # 实际所有结果
    if jsonpath(res_json, pattern_items_all) is False:
        testcase.fail("no results matched.\nExpected result: %s\nActual response:%s\npayload:%s" % (
            expected_result, testcase.response.text, testcase.payload))

    actual_result_all = [{field: item[field] for field in result_fields} for item in
                             jsonpath(res_json, pattern_items_all)]
    # 实际结果中仅取和预期结果的abbr相匹配的项进行比对
    pattern_items_matched = pattern_items_all.rstrip("*]")+"?(@.%s in %s)]"%(result_fields[0],repr(expected_base_values))
    actual_result_matched = jsonpath(res_json, pattern_items_matched)
    # logging.debug(actual_result_matched)

    if actual_result_matched is not False:

        acutal_result = [{field: item[field] for field in result_fields} for item in actual_result_matched]
        logging.debug(acutal_result)

        testcase.assertTrue(jsonmatch(expected_result, acutal_result),
                        "newsid: %s\nexpected result: %s\nactual result: %s" % (
                        testdata['newsid'], expected_result, acutal_result))
    else:
        testcase.fail(
            "no results matched.\nExpected result: %s\nActual result all:%s" % (expected_result, actual_result_all))

 